package com.sgb.kjwl.view.ui.fragment.self.pick;

import androidx.databinding.DataBindingUtil;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.android.material.tabs.TabLayout;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.swgk.core.util.LogUtil;
import com.sgb.kjwl.AppLazyFragment;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.FragmentSelfPickList4Binding;
import com.sgb.kjwl.di.self.DaggerSelfFragComponent;
import com.sgb.kjwl.di.self.SelfFragModule;
import com.sgb.jicai.event.JiCaiEventEntity;
import com.sgb.jicai.entity.JcCountEntity;
import com.sgb.kjwl.model.entity.self.SelfPickListEntity3;
import com.sgb.kjwl.utils.DisplayUtil;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.adapter.self.pick.SelfCollectAdapter;
import com.sgb.kjwl.viewmodel.self.collect.SelfPickListFragModel4;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.dialog.CommonDialog;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration;
import com.swgk.core.xrecyclerview.XRecyclerView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.List;

import javax.inject.Inject;

/**
 * 个人中心我的集采、我的加盟，二级页面
 */
public class SelfPickListFragment4 extends AppLazyFragment {
    private FragmentSelfPickList4Binding binding;
    @Inject
    SelfPickListFragModel4 viewModel;
    public static String CATEGORY = "category";
    public static String KEY_TYPE = "type";
    public static String KEY_STATUS = "status";
    //1.我的集采   2.我的加盟
    private int type;
    // 类别： 1.商品集采、2.机械集采 、3.设备集采、 4 劳务集采  5房产集采  6租赁集采
    private int category;
    //  状态--全部、集采中、集采完成、集采失败
    private int status;
    private SelfCollectAdapter adapter;
    private String keyWords = "";//搜索关键词

    //访问列表的固定字段可以传递进来
    public static SelfPickListFragment4 newInstance(int type, int category, int status) {
        SelfPickListFragment4 fragment = new SelfPickListFragment4();
        Bundle bundle = new Bundle();
        bundle.putInt(KEY_TYPE, type);
        bundle.putInt(CATEGORY, category);
        bundle.putInt(KEY_STATUS, status);
        fragment.setArguments(bundle);
        return fragment;
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerSelfFragComponent.builder()
                .appComponent(appComponent)
                .selfFragModule(new SelfFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_self_pick_list4, container, false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        type = getArguments().getInt(KEY_TYPE);
        category = getArguments().getInt(CATEGORY);
        status = getArguments().getInt(KEY_STATUS);
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    protected void onLazyLoad() {
        initTitle();
        initData();
    }

    public void initData() {
        viewModel.type.set(String.valueOf(type));// 1 我发起的  2 我加盟的
        viewModel.groupClass.set(String.valueOf(category));//集采分类 1商品集采 2 机械集采 3 设备集采 4 劳务集采  5房产集采  6租赁集采
        viewModel.status.set(String.valueOf(status));//订单状态  0全部  1 进行中2 已完成 4 集采失败
        viewModel.goodsName.set(keyWords);
        viewModel.getList(false);
        getTabNum();
    }

    @Override
    protected void initView() {
        if (adapter == null) {
            adapter = new SelfCollectAdapter(getActivity(), null);
        }
        adapter.setType(String.valueOf(type));
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        binding.recyclerView.setLayoutManager(layoutManager);
        binding.recyclerView.addItemDecoration(new RecyclerCustomDecoration(0, 0, 0, getActivity().getResources().getDimension(R.dimen.dp1), getActivity().getResources().getColor(R.color.color_F5F5F5)));
        binding.recyclerView.setLoadingMoreEnabled(true);
        binding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                viewModel.getList(false);
            }

            @Override
            public void onLoadMore() {

                if (viewModel.hasNext) {
                    viewModel.getList(true);
                } else {
                    binding.recyclerView.loadMoreComplete();
                }

            }
        });
        binding.recyclerView.setAdapter(adapter);

        adapter.setOnItemClick(new AdapterOnItemClick<SelfPickListEntity3>() {
            @Override
            public void onItemClick(SelfPickListEntity3 selfPickListEntity3, int position) {
                if (type == 1) {//需方发起
                    viewModel.getH5Url(selfPickListEntity3.getNo(), 1);
                } else if (type == 2) {//我的加盟
                    viewModel.getMyJoinH5Url(selfPickListEntity3.getNo(), selfPickListEntity3.getStatus(), selfPickListEntity3.getGroupBuyType());
                }
            }
        });

        adapter.setItemCallBack(new SelfCollectAdapter.ItemCallBack() {
            //需方发起--停止集采
            @Override
            public void stop(String id) {
                String msg = "您确认停止此次集采？";
                new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                        .setTitle("温馨提示")
                        .setMsg(msg)
                        .setDialogCallBack(new CommonDialog.DialogCallBack() {
                            @Override
                            public void onRightClick() {
                                //我的集采根据id停止集采
                                viewModel.stopJiCai(id);
                            }

                            @Override
                            public void onLeftClick() {

                            }
                        }).show();
            }

            //我的加盟--退出加盟
            @Override
            public void exit(String id) {
                String msg = "您确认退出此次集采？";
                new CommonDialog(getActivity()).builder().setPositiveButton("确定").setNegativeButton("取消")
                        .setTitle("温馨提示")
                        .setMsg(msg)
                        .setDialogCallBack(new CommonDialog.DialogCallBack() {
                            @Override
                            public void onRightClick() {
                                //我的加盟根据id退出集采
                                viewModel.exitJiCai(id);
                            }

                            @Override
                            public void onLeftClick() {

                            }
                        }).show();
            }

            //我的加盟--修改加盟信息
            @Override
            public void reedit(String id) {
                //我的加盟根据id修改加盟信息
//                JoinInJiCaiActivity.start(getActivity(), id, "", 2);//Jid没有，在修改加盟信息页面获取
            }
        });

        binding.recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                 /*
                SCROLL_STATE_IDLE:停止滚动
                SCROLL_STATE_DRAGGING: 用户慢慢拖动
                SCROLL_STATE_SETTLING：惯性滚动
                */
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {//SCROLL_STATE_IDLE:停止滚动

                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (layoutManager.findFirstVisibleItemPosition() > 1) {
                    binding.imgBackTop.setVisibility(View.VISIBLE);
                } else {
                    binding.imgBackTop.setVisibility(View.GONE);
                }
            }
        });
        binding.imgBackTop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.recyclerView.scrollToPosition(0);
            }
        });

    }

    private void initTitle() {
        setTypeDatas();
    }

    public void setTypeDatas() {
        binding.tabLayout.addTab(binding.tabLayout.newTab());
        binding.tabLayout.addTab(binding.tabLayout.newTab());
        binding.tabLayout.addTab(binding.tabLayout.newTab());
        binding.tabLayout.addTab(binding.tabLayout.newTab());
        binding.tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        setTabTitleSize(binding.tabLayout.getTabAt(0), "全部" + " (0)");
        setTabTitleSize(binding.tabLayout.getTabAt(1), "进行中" + " (0)");
        setTabTitleSize(binding.tabLayout.getTabAt(2), "集采完成" + " (0)");
        setTabTitleSize(binding.tabLayout.getTabAt(3), "集采失败" + " (0)");
        binding.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (3 == tab.getPosition()) {
                    status = 4;
                } else {
                    status = tab.getPosition();
                }
                LogUtil.v("api", "type:" + type + "###category:" + category + "###status:" + status);
                //刷新页面数据
                initData();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    public void showUrl(String url) {
        WebViewX5HostActivity.start(getActivity(), url);
    }

    public void showList(List<SelfPickListEntity3> list, boolean isLoadMore) {
        if (isLoadMore) {
            binding.recyclerView.loadMoreComplete();
            if (list.size() != 0) {
                adapter.addDatas(list);
            }
        } else {
            if (list.size() == 0) {
                binding.emptyView.setVisibility(View.VISIBLE);
                binding.imgBackTop.setVisibility(View.GONE);
            } else {
                binding.emptyView.setVisibility(View.GONE);
            }
            binding.recyclerView.refreshComplete();
            binding.recyclerView.setLoadingMoreEnabled(true);
            adapter.setDatas(list);
        }
        getTabNum();
    }

    private void setTabTitleSize(TabLayout.Tab tab, String text) {
        if (null == tab) {//多个fragment已创建，但是懒加载时后面的页面还没有初始化tab
            return;
        }
        int start = text.indexOf("(");
        int end = text.length();
        SpannableString textSpan = new SpannableString(text);
        textSpan.setSpan(new AbsoluteSizeSpan(DisplayUtil.sp2px(getContext(), 14)), 0, start, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        textSpan.setSpan(new AbsoluteSizeSpan(DisplayUtil.sp2px(getContext(), 10)), start, end, Spannable.SPAN_INCLUSIVE_INCLUSIVE);
        tab.setText(textSpan);
    }

    public void getTabNum() {
        viewModel.getMyGroupBuyListCount(type, category, keyWords);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(JiCaiEventEntity event) {
        if (event.getCode() == EventConstant.EVENT_JICAI_MY_CEN_AND_JOIN) {
            keyWords = event.getName();
            initData();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void setTabNum(List<JcCountEntity> numList) {
        if (null == numList || numList.size() == 0) {
            return;
        }
        for (JcCountEntity entity : numList) {
            String num = " (" + (Integer.valueOf(entity.getCount()) > 99 ? "99+" : entity.getCount()) + ")";
            switch (Integer.valueOf(entity.getStatus())) {//012
                case 0:
                    setTabTitleSize(binding.tabLayout.getTabAt(0), "全部" + num);
                    break;
                case 1:
                    setTabTitleSize(binding.tabLayout.getTabAt(1), "进行中" + num);
                    break;
                case 2:
                    setTabTitleSize(binding.tabLayout.getTabAt(2), "集采完成" + num);
                    break;
                case 4:
                    setTabTitleSize(binding.tabLayout.getTabAt(3), "集采失败" + num);
                    break;
            }
        }
    }
}
